<?php
/**
 * certificate element class
 *
 * @final
 * @author raphael seebacher <raphasee@ee.ethz.ch>
 * @version 0.01
 */
final class certificate extends message_element_controller {
    protected $parameters = Array(
      'certificate_signing_request',
    );

    public function get_tag() {
        return 'certificate';
    }

    protected function process_element() {
        $this->check_content_parameters_all_present();

        $uc = user_controller::get_instance();
        $user = $uc->get_user();

        $rate_limit = config::get(
          'certificate',
          'max_certificates_issued_per_day_per_user'
        );

        try {
            $certificate = $user->get_current_certificate();
            $issued = DateTime::createFromFormat(
              'Y-m-d H:i:s',
              $certificate->get('issued')
            );

            if (time() < $issued->getTimestamp()+86400/$rate_limit) {
                throw new error(
                  'Certificate signing rate limited: max '
                  .$rate_limit.' certificate signings per user per day!'
                );
            }
            else {
                $certificate->revoke();
            }
        }
        catch (model_exception $e) {

        }

        $csr_raw = base64_decode($this->content['certificate_signing_request']);
        $csr = new certificate_signing_request($csr_raw);

        try {
            $csr->sign_request($user);
            $certificate_raw = $csr->get_signed_certificate();
        }
        catch (model_exception $e) {
            throw new error($e->getMessage());
        }

        $uc = user_certificate::construct_from_x509_certificate(
          $certificate_raw,
          $user->get_id()
        );
        $uc->save();

        return Array(
          'status' => 'ok',
          'signed_certificate' => $certificate_raw,
        );
    }
}
?>